package cn.wolfcode.ssm.controller;

import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.domain.Notice;
import cn.wolfcode.ssm.mapper.NoticeMapper;
import cn.wolfcode.ssm.qo.JsonResult;
import cn.wolfcode.ssm.qo.QueryObject;
import cn.wolfcode.ssm.service.INoticeService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private INoticeService noticeService;

   @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo")QueryObject qo) {
        PageInfo<Notice> pageInfo = noticeService.selctForPageResult(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "notice/list";
    }


   @RequestMapping("/show")
    public String show(Model model,Long id) {
       Notice notice = noticeService.getOne(id);
       model.addAttribute("notice",notice);
       Employee employee =(Employee) SecurityUtils.getSubject().getPrincipal();
       //拿到当前用户读过的所有通告id
       List<Long> noticeIds=noticeService.getNotice(employee.getId());
       //如果该集合不包括当前通告的id,就插入两者之间的关系
       if(!noticeIds.contains(notice.getId())){
           noticeService.insertRelation(id,employee.getId());
       }
       return "notice/show";
    }


    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
            if (id != null) {
                noticeService.deleteRelation(id);
                noticeService.delete(id);
            }
            return new JsonResult();
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Notice dept) {
            if (dept.getId() != null) {
                noticeService.update(dept);
            } else {
                noticeService.save(dept);
            }
            return new JsonResult();
    }

}
